package com.hm.service.service.spark.count;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.time.Duration;
import java.time.Instant;


/**
 * 请求规则 服务
 * 请求次数，请求频率等等
 */
@Service
public class RuleService implements IRuleService {
    private static final Logger logger = LoggerFactory.getLogger(RuleService.class);

    //10秒
    public static final long INTERVAL_TIME = 1000 * 10;

    @Qualifier("jedisPool")
    private final JedisPool jedisPool;

    private static final String requestTime = "request_time_";

    public RuleService(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    @Override
    public String timeDifference(String userId) {
        try (Jedis jedis = jedisPool.getResource()) {
            //根据userId获取对应的token
            String key = requestTime + userId;
            boolean exists = jedis.exists(key);
            if (exists) {
                String requestTime = jedis.get(key);
                long timeDifference = calculateTimeDifference(Long.parseLong(requestTime), System.currentTimeMillis());
                if (timeDifference > INTERVAL_TIME) {
                    //颁发时间到了
                    return "";
                } else {
                    return "0";
                }
            } else {
                return "";
            }
        }
    }

    @Override
    public void setTag(String userId) {
        try (Jedis jedis = jedisPool.getResource()) {
            //根据userId获取对应的token
            String key = requestTime + userId;
            jedis.set(key, String.valueOf(System.currentTimeMillis()));
        }
    }

    private static long calculateTimeDifference(long timestamp1, long timestamp2) {
        // 将时间戳转换为Instant对象
        Instant instant1 = Instant.ofEpochMilli(timestamp1);
        Instant instant2 = Instant.ofEpochMilli(timestamp2);
        // 计算时间差并返回结果（单位：毫秒）
        Duration duration = Duration.between(instant1, instant2);
        return duration.toMillis();
    }
}
